
# import time
# import asyncio
# from typing import Optional, Dict, Any
# from tortoise import Tortoise, connections
# from tortoise.exceptions import DBConnectionError, OperationalError
# from datetime import datetime

# from app.core.config import settings
# from app.utils.app_log import logger
# from app.models import TORTOISE_ORM_MODELS


# class DatabaseManager:
#     """数据库管理器"""
    
#     def __init__(self):
#         self.is_initialized = False
        
#     def get_database_config(self) -> Dict[str, Any]:
#         """获取数据库配置"""
#         return {
#             "connections": {
#                 "default": {
#                     "engine": "tortoise.backends.mysql",
#                     "credentials": {
#                         "host": settings.database_host,
#                         "port": settings.database_port,
#                         "user": settings.database_user,
#                         "password": settings.database_password,
#                         "database": settings.database_name,
#                         "minsize": 1,
#                         "maxsize": settings.database_pool_size,
#                         "charset": "utf8mb4",
#                         "echo": settings.database_echo
#                     }
#                 }
#             },
#             "apps": {
#                 "models": {
#                     "models": TORTOISE_ORM_MODELS + ["aerich.models"],
#                     "default_connection": "default",
#                 }
#             },
#             "timezone": "Asia/Shanghai"
#         }
    
#     async def check_database_connection(self) -> bool:
#         """检查数据库连接"""
#         try:
#             config = self.get_database_config()
#             await Tortoise.init(config=config)
            
#             # 测试连接
#             connection = connections.get("default")
#             await connection.execute_query("SELECT 1")
            
#             await Tortoise.close_connections()
#             logger.info("数据库连接测试成功")
#             return True
            
#         except Exception as e:
#             logger.error(f"数据库连接测试失败: {str(e)}")
#             return False
    
#     async def create_database_if_not_exists(self) -> bool:
#         """创建数据库（如果不存在）"""
#         try:
#             # 先连接到mysql系统数据库
#             database_name = settings.database_name
#             system_config = self.get_database_config()
#             system_config["connections"]["default"]["credentials"]["database"] = "mysql"
            
#             await Tortoise.init(config=system_config)
#             connection = connections.get("default")
            
#             # 检查数据库是否存在
#             result = await connection.execute_query(
#                 f"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{database_name}'"
#             )
            
#             if not result[1]:  # 数据库不存在
#                 # 创建数据库
#                 await connection.execute_query(
#                     f"CREATE DATABASE IF NOT EXISTS `{database_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
#                 )
#                 logger.info(f"数据库 {database_name} 创建成功")
#             else:
#                 logger.info(f"数据库 {database_name} 已存在")
            
#             await Tortoise.close_connections()
#             return True
            
#         except Exception as e:
#             logger.error(f"创建数据库失败: {str(e)}")
#             return False
    
#     async def initialize_database(self, create_tables: bool = True) -> bool:
#         """初始化数据库"""
#         # 检查是否启用数据库功能
#         if not settings.enable_database:
#             logger.info("数据库功能已禁用，跳过初始化")
#             return True
            
#         start_time = time.time()
        
#         try:
#             logger.info("开始初始化数据库...")
            
#             # 1. 检查数据库连接
#             if not await self.check_database_connection():
#                 # 尝试创建数据库
#                 if not await self.create_database_if_not_exists():
#                     raise Exception("无法创建数据库")
            
#             # 2. 初始化Tortoise-ORM
#             config = self.get_database_config()
#             await Tortoise.init(config=config)
            
#             # 3. 创建数据表
#             if create_tables and settings.database_auto_create:
#                 await Tortoise.generate_schemas()
#                 logger.info("数据表创建/更新完成")
            
#             # 4. 记录初始化日志（只在启用数据库时）
#             if settings.enable_database:
#                 await self._log_database_init("success", time.time() - start_time)
            
#             self.is_initialized = True
#             logger.info(f"数据库初始化完成，耗时: {time.time() - start_time:.2f}秒")
#             return True
            
#         except Exception as e:
#             error_msg = f"数据库初始化失败: {str(e)}"
#             logger.error(error_msg)
            
#             # 记录失败日志
#             if settings.enable_database:
#                 try:
#                     await self._log_database_init("failed", time.time() - start_time, error_msg)
#                 except:
#                     pass
                
#             return False
    
#     async def _log_database_init(self, status: str, execution_time: float, message: str = None):
#         """记录数据库初始化日志"""
#         try:
#             from app.models.base.system import DatabaseInitLog
            
#             await DatabaseInitLog.create(
#                 version="1.0.0",
#                 init_type="auto",
#                 status=status,
#                 message=message or f"数据库初始化{status}",
#                 execution_time=execution_time
#             )
#         except Exception as e:
#             logger.warning(f"记录初始化日志失败: {str(e)}")
    
#     async def close_database(self):
#         """关闭数据库连接"""
#         try:
#             await Tortoise.close_connections()
#             self.is_initialized = False
#             logger.info("数据库连接已关闭")
#         except Exception as e:
#             logger.error(f"关闭数据库连接失败: {str(e)}")
    
#     async def init_default_data(self):
#         """初始化默认数据"""
#         # 检查是否启用自动初始化数据
#         if not settings.enable_auto_init_data:
#             logger.info("自动初始化数据功能已禁用，跳过初始化")
#             return
            
#         # 检查是否启用数据库
#         if not settings.enable_database:
#             logger.info("数据库功能已禁用，跳过默认数据初始化")
#             return
            
#         try:
#             logger.info("开始初始化默认数据...")
            
#             # 创建默认管理员用户（只在启用用户系统时）
#             if settings.enable_user_system:
#                 await self._create_default_admin()
            
#             # 创建默认系统配置
#             await self._create_default_configs()
            
#             logger.info("默认数据初始化完成")
            
#         except Exception as e:
#             logger.error(f"初始化默认数据失败: {str(e)}")
    
#     async def _create_default_admin(self):
#         """创建默认管理员用户"""
#         # 检查是否启用用户系统
#         if not settings.enable_user_system:
#             logger.info("用户系统已禁用，跳过默认管理员创建")
#             return
            
#         try:
#             from app.models import User
#             from app.utils.user import get_password_hash
            
#             # 检查是否已存在管理员
#             admin_exists = await User.filter(username="admin", is_deleted=False).exists()
            
#             if not admin_exists:
#                 admin_user = await User.create(
#                     username="admin",
#                     email="admin@example.com",
#                     hashed_password=get_password_hash("123456"),
#                     full_name="系统管理员",
#                     is_active=True,
#                     is_superuser=True
#                 )
#                 logger.info(f"默认管理员用户创建成功: {admin_user.username}")
#             else:
#                 logger.info("默认管理员用户已存在")
                
#         except Exception as e:
#             logger.error(f"创建默认管理员失败: {str(e)}")
    
#     async def _create_default_configs(self):
#         """创建默认系统配置"""
#         try:
#             from app.models import SystemConfig
            
#             default_configs = [
#                 {
#                     "key": "system_name", 
#                     "value": "FastAPI通用基础项目", 
#                     "description": "系统名称",
#                     "config_type": "string",
#                     "is_public": True
#                 },
#                 {
#                     "key": "system_version", 
#                     "value": "1.0.0", 
#                     "description": "系统版本",
#                     "config_type": "string",
#                     "is_public": True
#                 },
#                 {
#                     "key": "enable_user_registration", 
#                     "value": str(settings.enable_user_registration), 
#                     "description": "是否启用用户注册",
#                     "config_type": "boolean",
#                     "is_public": True
#                 },
#                 {
#                     "key": "max_login_attempts", 
#                     "value": "5", 
#                     "description": "最大登录尝试次数",
#                     "config_type": "integer",
#                     "is_public": False
#                 },
#                 {
#                     "key": "session_timeout", 
#                     "value": "3600", 
#                     "description": "会话超时时间(秒)",
#                     "config_type": "integer",
#                     "is_public": False
#                 }
#             ]
            
#             for config_data in default_configs:
#                 await SystemConfig.set_config(**config_data)
            
#             logger.info("默认系统配置创建完成")
            
#         except Exception as e:
#             logger.error(f"创建默认系统配置失败: {str(e)}")
    
#     async def get_database_status(self) -> Dict[str, Any]:
#         """获取数据库状态信息"""
#         try:
#             if not self.is_initialized:
#                 return {
#                     "status": "disconnected",
#                     "message": "数据库未初始化"
#                 }
            
#             # 检查连接状态
#             connection = connections.get("default")
#             await connection.execute_query("SELECT 1")
            
#             # 获取数据库信息
#             tables_result = await connection.execute_query(
#                 "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE()"
#             )
            
#             return {
#                 "status": "connected",
#                 "database_name": settings.database_name,
#                 "host": settings.database_host,
#                 "port": settings.database_port,
#                 "tables_count": len(tables_result[1]) if tables_result[1] else 0,
#                 "tables": [row[0] for row in tables_result[1]] if tables_result[1] else [],
#                 "connection_pool_size": settings.database_pool_size
#             }
            
#         except Exception as e:
#             return {
#                 "status": "error",
#                 "message": str(e)
#             }


# # 全局数据库管理器实例
# db_manager = DatabaseManager()


# # 便捷函数
# async def init_database() -> bool:
#     """初始化数据库的便捷函数"""
#     return await db_manager.initialize_database()


# async def close_database():
#     """关闭数据库连接的便捷函数"""
#     await db_manager.close_database()


# async def get_database_status() -> Dict[str, Any]:
#     """获取数据库状态的便捷函数"""
#     return await db_manager.get_database_status()














# # """
# # 数据库管理API接口
# # 提供数据库状态查看、初始化等功能
# # """
# # ## 注： 是示例性质的 无实际作用 。不知道正常系统开发会不会给数据库留操作接口 感觉应该不会。
# # from datetime import datetime
# # from typing import List, Dict, Any
# # from fastapi import APIRouter, Depends, Query
# # from tortoise.queryset import QuerySet

# # from app.core.auth import get_current_superuser, get_current_user_required
# # from app.schemas.base.login import JWTPayload
# # from app.utils.request import RequestHandler
# # from app.core.database import db_manager, get_database_status
# # from app.models.base.system import DatabaseInitLog, SystemConfig, OperationLog
# # from app.models.base.user import User, UserLoginLog

# # router = APIRouter()


# # @router.get("/status", summary="获取数据库状态")
# # async def get_db_status(
# #     current_user: JWTPayload = Depends(get_current_superuser)
# # ):
# #     """
# #     获取数据库状态信息
# #     需要超级用户权限
# #     """
# #     try:
# #         status_info = await get_database_status()
        
# #         return RequestHandler.success(
# #             data=status_info,
# #             message="数据库状态获取成功",
# #             remarks=f"管理员 {current_user.username} 查看数据库状态"
# #         )
        
# #     except Exception as e:
# #         return RequestHandler.server_error(
# #             message="获取数据库状态失败",
# #             remarks=f"错误详情: {str(e)}"
# #         )


# # @router.post("/init", summary="重新初始化数据库")
# # async def reinit_database(
# #     current_user: JWTPayload = Depends(get_current_superuser),
# #     create_tables: bool = Query(True, description="是否创建数据表"),
# #     init_data: bool = Query(True, description="是否初始化默认数据")
# # ):
# #     """
# #     重新初始化数据库
# #     需要超级用户权限，谨慎操作
# #     """
# #     try:
# #         # 重新初始化数据库
# #         success = await db_manager.initialize_database(create_tables=create_tables)
        
# #         if not success:
# #             return RequestHandler.server_error(
# #                 message="数据库初始化失败",
# #                 remarks="请检查数据库配置和连接"
# #             )
        
# #         # 初始化默认数据
# #         if init_data:
# #             await db_manager.init_default_data()
        
# #         return RequestHandler.success(
# #             data={
# #                 "initialization_time": datetime.now().isoformat(),
# #                 "create_tables": create_tables,
# #                 "init_data": init_data,
# #                 "operator": current_user.username
# #             },
# #             message="数据库重新初始化成功",
# #             remarks="数据库已重新初始化，所有表结构已更新"
# #         )
        
# #     except Exception as e:
# #         return RequestHandler.server_error(
# #             message="数据库初始化失败",
# #             remarks=f"错误详情: {str(e)}"
# #         )


# # @router.get("/init-logs", summary="获取数据库初始化日志")
# # async def get_init_logs(
# #     current_user: JWTPayload = Depends(get_current_superuser),
# #     page: int = Query(1, ge=1, description="页码"),
# #     page_size: int = Query(20, ge=1, le=100, description="每页数量")
# # ):
# #     """
# #     获取数据库初始化日志
# #     需要超级用户权限
# #     """
# #     try:
# #         # 计算偏移量
# #         offset = (page - 1) * page_size
        
# #         # 查询日志
# #         logs = await DatabaseInitLog.filter(is_deleted=False).order_by('-created_at').offset(offset).limit(page_size)
# #         total = await DatabaseInitLog.filter(is_deleted=False).count()
        
# #         # 转换为字典格式
# #         log_data = []
# #         for log in logs:
# #             log_data.append({
# #                 "id": log.id,
# #                 "version": log.version,
# #                 "init_type": log.init_type,
# #                 "status": log.status,
# #                 "message": log.message,
# #                 "execution_time": log.execution_time,
# #                 "created_at": log.created_at.isoformat()
# #             })
        
# #         return RequestHandler.success(
# #             data={
# #                 "logs": log_data,
# #                 "pagination": {
# #                     "page": page,
# #                     "page_size": page_size,
# #                     "total": total,
# #                     "total_pages": (total + page_size - 1) // page_size
# #                 }
# #             },
# #             message="初始化日志获取成功",
# #             remarks=f"共 {total} 条初始化记录"
# #         )
        
# #     except Exception as e:
# #         return RequestHandler.server_error(
# #             message="获取初始化日志失败",
# #             remarks=f"错误详情: {str(e)}"
# #         )


# # @router.get("/tables", summary="获取数据表信息")
# # async def get_tables_info(
# #     current_user: JWTPayload = Depends(get_current_superuser)
# # ):
# #     """
# #     获取数据库表信息
# #     需要超级用户权限
# #     """
# #     try:
# #         # 获取所有模型的统计信息
# #         tables_info = []
        
# #         # 用户相关表
# #         user_count = await User.filter(is_deleted=False).count()
# #         login_log_count = await UserLoginLog.filter(is_deleted=False).count()
        
# #         tables_info.extend([
# #             {
# #                 "table_name": "users",
# #                 "model_name": "User",
# #                 "description": "用户表",
# #                 "record_count": user_count
# #             },
# #             {
# #                 "table_name": "user_login_logs", 
# #                 "model_name": "UserLoginLog",
# #                 "description": "用户登录日志表",
# #                 "record_count": login_log_count
# #             }
# #         ])
        
# #         # 系统相关表
# #         config_count = await SystemConfig.filter(is_deleted=False).count()
# #         operation_log_count = await OperationLog.filter(is_deleted=False).count()
# #         init_log_count = await DatabaseInitLog.filter(is_deleted=False).count()
        
# #         tables_info.extend([
# #             {
# #                 "table_name": "system_configs",
# #                 "model_name": "SystemConfig", 
# #                 "description": "系统配置表",
# #                 "record_count": config_count
# #             },
# #             {
# #                 "table_name": "operation_logs",
# #                 "model_name": "OperationLog",
# #                 "description": "操作日志表", 
# #                 "record_count": operation_log_count
# #             },
# #             {
# #                 "table_name": "database_init_logs",
# #                 "model_name": "DatabaseInitLog",
# #                 "description": "数据库初始化日志表",
# #                 "record_count": init_log_count
# #             }
# #         ])
        
# #         return RequestHandler.success(
# #             data={
# #                 "tables": tables_info,
# #                 "total_tables": len(tables_info),
# #                 "query_time": datetime.now().isoformat()
# #             },
# #             message="数据表信息获取成功",
# #             remarks="显示所有模型对应的数据表统计信息"
# #         )
        
# #     except Exception as e:
# #         return RequestHandler.server_error(
# #             message="获取数据表信息失败", 
# #             remarks=f"错误详情: {str(e)}"
# #         )


# # @router.get("/configs", summary="获取系统配置")
# # async def get_system_configs(
# #     current_user: JWTPayload = Depends(get_current_user_required),
# #     public_only: bool = Query(False, description="是否只显示公开配置")
# # ):
# #     """
# #     获取系统配置
# #     普通用户只能查看公开配置，超级用户可以查看所有配置
# #     """
# #     try:
# #         # 根据用户权限决定查询条件
# #         if current_user.is_superuser and not public_only:
# #             configs = await SystemConfig.filter(is_deleted=False).order_by('key')
# #         else:
# #             configs = await SystemConfig.filter(is_deleted=False, is_public=True).order_by('key')
        
# #         # 转换为字典格式
# #         config_data = []
# #         for config in configs:
# #             config_info = {
# #                 "key": config.key,
# #                 "value": config.value,
# #                 "description": config.description,
# #                 "config_type": config.config_type,
# #                 "is_public": config.is_public,
# #                 "updated_at": config.updated_at.isoformat()
# #             }
            
# #             # 非超级用户不显示敏感信息
# #             if not current_user.is_superuser and not config.is_public:
# #                 config_info["value"] = "***"
                
# #             config_data.append(config_info)
        
# #         return RequestHandler.success(
# #             data={
# #                 "configs": config_data,
# #                 "total": len(config_data),
# #                 "user_type": "superuser" if current_user.is_superuser else "normal_user",
# #                 "public_only": public_only or not current_user.is_superuser
# #             },
# #             message="系统配置获取成功",
# #             remarks=f"用户 {current_user.username} 查看系统配置"
# #         )
        
# #     except Exception as e:
# #         return RequestHandler.server_error(
# #             message="获取系统配置失败",
# #             remarks=f"错误详情: {str(e)}"
# #         )


# # @router.put("/configs/{config_key}", summary="更新系统配置")
# # async def update_system_config(
# #     config_key: str,
# #     value: str,
# #     current_user: JWTPayload = Depends(get_current_superuser),
# #     description: str = Query(None, description="配置描述"),
# #     config_type: str = Query("string", description="配置类型")
# # ):
# #     """
# #     更新系统配置
# #     需要超级用户权限
# #     """
# #     try:
# #         # 更新配置
# #         config = await SystemConfig.set_config(
# #             key=config_key,
# #             value=value,
# #             description=description,
# #             config_type=config_type
# #         )
        
# #         return RequestHandler.success(
# #             data={
# #                 "key": config.key,
# #                 "value": config.value,
# #                 "description": config.description,
# #                 "config_type": config.config_type,
# #                 "updated_by": current_user.username,
# #                 "updated_at": config.updated_at.isoformat()
# #             },
# #             message="系统配置更新成功",
# #             remarks=f"配置 {config_key} 已由管理员 {current_user.username} 更新"
# #         )
        
# #     except Exception as e:
# #         return RequestHandler.server_error(
# #             message="更新系统配置失败",
# #             remarks=f"错误详情: {str(e)}"
# #         )


# # @router.get("/statistics", summary="获取数据库统计信息")
# # async def get_database_statistics(
# #     current_user: JWTPayload = Depends(get_current_superuser)
# # ):
# #     """
# #     获取数据库统计信息
# #     需要超级用户权限
# #     """
# #     try:
# #         # 统计各表数据量
# #         stats = {
# #             "users": {
# #                 "total": await User.all().count(),
# #                 "active": await User.filter(is_active=True, is_deleted=False).count(),
# #                 "superusers": await User.filter(is_superuser=True, is_deleted=False).count(),
# #                 "today_registered": await User.filter(
# #                     created_at__gte=datetime.now().replace(hour=0, minute=0, second=0, microsecond=0),
# #                     is_deleted=False
# #                 ).count()
# #             },
# #             "login_logs": {
# #                 "total": await UserLoginLog.all().count(),
# #                 "today": await UserLoginLog.filter(
# #                     login_time__gte=datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
# #                 ).count(),
# #                 "successful": await UserLoginLog.filter(login_success=True).count(),
# #                 "failed": await UserLoginLog.filter(login_success=False).count()
# #             },
# #             "system": {
# #                 "configs": await SystemConfig.filter(is_deleted=False).count(),
# #                 "operation_logs": await OperationLog.filter(is_deleted=False).count(),
# #                 "init_logs": await DatabaseInitLog.filter(is_deleted=False).count()
# #             }
# #         }
        
# #         return RequestHandler.success(
# #             data={
# #                 "statistics": stats,
# #                 "generated_at": datetime.now().isoformat(),
# #                 "generated_by": current_user.username
# #             },
# #             message="数据库统计信息获取成功",
# #             remarks="实时统计数据"
# #         )
        
# #     except Exception as e:
# #         return RequestHandler.server_error(
# #             message="获取统计信息失败",
# #             remarks=f"错误详情: {str(e)}"
# #         )